package com.budwk.app.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StrUtil {

    private static final Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 格式化字符串：如果字符串是否为空 返回空字符
     * @param str
     * @return
     */
    public static String formatStr(String str) {
        return StringUtils.isNotEmpty(str) ? str : StringUtils.EMPTY;
    }

    /**
     * 将对象空值转为-
     */
    public static Sqfw_formSummary formatSummaryNullStr(Sqfw_formSummary sqfwFormSummary) {
        JSONObject jsonObject = formatSummaryNullToJson(sqfwFormSummary);
        return JSONObject.toJavaObject(jsonObject, Sqfw_formSummary.class);
    }

    /**
     * 讲obj对象的属性为空的赋值 -
     * @param obj 对象
     * @return json对象
     */
    public static JSONObject formatSummaryNullToJson(Object obj) {
        Class<? extends Object> clazz = obj.getClass();
        // 获取类中声明的字段
        Field[] fields = clazz.getDeclaredFields();
        JSONObject jsonObject = new JSONObject();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if ("java.lang.String".equals(field.getType().getName())) {
                    String value = String.valueOf(field.get(obj));
                    if (StringUtils.isEmpty(value) || "null".equals(value)) {
                        jsonObject.put(field.getName(), "-");
                        continue;
                    }
                }
                jsonObject.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                log.error("formatNullStr error: ", e);
            }
        }
        return jsonObject;
    }

    /**
     * 处理所有的字符串空格情况
     * @param obj
     */
    public static void handleStrTrim(Object obj) {
        for (Field field : obj.getClass().getDeclaredFields()) {
            try {
                field.setAccessible(true);
                if ("java.lang.String".equals(field.getType().getName())) {
                    String value = (String) field.get(obj);
                    if (value != null) {
                        field.set(obj, value.replaceAll("\\s", "")
                                .replaceAll("\\n", "")
                                .replaceAll("\\r", "")); // 删除所有空格、回车、换行
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下划线转驼峰
     * @param str 字符串
     * @return 转换后的字符串
     */
    public static String lineToHump(String str) {
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    // 获取房屋地址
    public static String getHouseAddress(Sqfw_formSummary summary) {
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotEmpty(summary.getA1())) {
            sb.append(summary.getA1());
        }
        String a4 = summary.getA4();
        if (StringUtils.isNotEmpty(a4)) {
            // 获取最后一个字符串
            String lastStr = a4.substring(a4.length() - 1);
            if (!lastStr.equals("栋")) {
                sb.append(String.format("%s%s", a4, "栋"));
            } else {
                sb.append(a4);
            }
        }
        if (StringUtils.isNotEmpty(summary.getA5())) {
            sb.append(summary.getA5());
        }
        return sb.toString();
    }

    public static String getHouseAddress(Sqfw_cenSusPaper summary) {
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotEmpty(summary.getCourtyard())) {
            sb.append(summary.getCourtyard());
        }
        String building = summary.getBuilding();
        if (StringUtils.isNotEmpty(building)) {
            // 获取最后一个字符串
            String lastStr = building.substring(building.length() - 1);
            if (!lastStr.equals("栋")) {
                sb.append(String.format("%s%s", building, "栋"));
            } else {
                sb.append(building);
            }
        }
        String houseNumber = summary.getHouseNumber();
        if (StringUtils.isNotEmpty(houseNumber)) {
            // 获取最后一个字符串
            String lastStr = houseNumber.substring(houseNumber.length() - 1);
            if (!lastStr.equals("号")) {
                sb.append(String.format("%s%s", houseNumber, "号"));
            } else {
                sb.append(houseNumber);
            }
        }
        return sb.toString();
    }

    /**
     * 替换空字符串
     * @param str 字符串
     * @return 如果为空 替换为-
     */
    public static String replaceNullStr(String str) {
        return StringUtils.isNotEmpty(str) ? str : CommonConstants.HORIAONTAL_LINE;
    }

    public static <T> T serializerData(Class<T> clazz, Object object) {
        String text = JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
        T t = JSON.parseObject(text, clazz);
        return t;
    }

    public static <T> T getNewClass(Class<?> cs)  {
        try {
            return (T) cs.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("class format:", e);
            throw new AppException("类转换异常！");
        }
    }

    /**
     * 对list中 返回jsonb的数据做处理
     * @param clazz
     * @param object
     * @return
     * @param <T>
     */
    public static <T> List<T> toListByJson(Class<T> clazz, Object object) {
        String value = JSONObject.parseObject(JSONObject.toJSONString(object)).getString("value");
        return JSONArray.parseArray(value, clazz);
    }

    /**
     * 把id集合转成sql in 的条件  例：('1','2','3') 或 (1,2,3)
     * @param ids
     * @return
     */
    public static String formatIds(List<?> ids) {
        if (ids == null || ids.size() == 0) return "('')";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        int i = 0;
        for (Object id : ids) {
            i ++;

            if (id instanceof String) {
                stringBuilder.append("'");
            }

            stringBuilder.append(id);

            if (id instanceof String) {
                stringBuilder.append("'");
            }

            if (i < ids.size()) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")");
        return stringBuilder.toString();
    }

    /**
     * 替换空字符串
     * @param str 字符串
     * @return 如果为空 替换为无
     */
    public static String replaceNullIsNo(String str) {
        return StringUtils.isNotEmpty(str) ? str : "无";
    }
    public static String getUUID() {
        return UuidUtils.generateUuid().replace("-", "");
    }
    public static String formatZhiShu(String str) {
        if (StringUtils.isEmpty(str)) {
            return StringUtils.EMPTY;
        }
        if (str.equals(CommonConstants.DIRECTLY_UNDER)) {
            return StringUtils.EMPTY;
        }
        return str;
    }
}
